﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using AgileDirect.SPDToolkit.Workflows.Foundation;

namespace AgileDirect.SPDToolkit.Workflows.Utility
{
    /// <summary>
    /// Program to export SPD workflows
    /// </summary>
    class Program
    {
        /// <summary>
        /// Main program 
        /// </summary>
        static void Main(string[] args)
        {
            var fullParameterString = string.Join(" ", args);
            var parameters = ParseParameterString(fullParameterString);

            if (parameters != null && parameters.Count != 5)
            {
                Console.WriteLine("SPD WORKFLOW FEATURE GENERATOR");
                Console.WriteLine("Utility to export SharePoint Designer generated workflows to features\n");
                Console.WriteLine("Usage:");
                Console.WriteLine("\t-path <Folder to store feature in>");
                Console.WriteLine("\t-name <Name of feature>");
                Console.WriteLine("\t-title <Title of the feature>");
                Console.WriteLine("\t-description <Description of the feature>");
                Console.WriteLine("\t-url <Url to the site to export workflows from>");
                Console.WriteLine("\n Created by Emile Bosch - http://agiledirect.wordpress.com / http://www.agiledirect.nl");
                return;
            }

            ExportWorkflowFeature(parameters);
        }

        /// <summary>
        /// Parse the parameters
        /// </summary>
        private static Dictionary<string, string> ParseParameterString(string fullParameterString)
        {
            var parameters = new Dictionary<string, string>();
            var parameterParts = fullParameterString.Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var parameterPart in parameterParts)
            {
                var keyvalue = parameterPart.Split(new[] { ' ' }, 2);
                parameters.Add(keyvalue[0].Trim().ToLower(), keyvalue[1].Trim());
            }
            return parameters;
        }

        /// <summary>
        /// Export workflow feature
        /// </summary>
        private static void ExportWorkflowFeature(IDictionary<string, string> parameters)
        {
            var guid = Guid.NewGuid();
            var path = parameters["path"];
            var featurename = parameters["name"];
            var title = parameters["title"];
            var description = parameters["description"];
            var url = parameters["url"];

            if (!Directory.Exists(path))
            {
                Console.WriteLine("Destination directory doesn't exist!");
                return;
            }

            string featurePath = Path.Combine(path, featurename);
            string workflowsPath = Path.Combine(featurePath, "Workflows\\");

            EnsurePathExists(featurePath);
            EnsurePathExists(workflowsPath);

            SPDWorkflowManager.ExportAllWorkflowInformation(url, workflowsPath);

            WriteFeatureDefinition(guid, title, description, featurePath, false);
        }

        /// <summary>
        /// Writes the feature definition to an file
        /// </summary>
        private static void WriteFeatureDefinition(Guid guid, string title, string description, string featurePath, bool overwrite)
        {
            string path = Path.Combine(featurePath, "Feature.xml");

            var sb = new StringBuilder();
            sb.AppendFormat("<Feature Id=\"{0}\"\n", guid);
            sb.AppendFormat("\t Title=\"{0}\"\n", title);
            sb.AppendFormat("\t Description=\"{0}\"\n", description);
            sb.AppendFormat("\t Scope=\"Web\"\n");
            sb.AppendFormat("\t Hidden=\"FALSE\"\n");
            sb.AppendFormat("\t ReceiverAssembly=\"{0}\"\n", typeof(SPDWorkflowReceiver).Assembly.FullName);
            sb.AppendFormat("\t ReceiverClass=\"{0}\"\n", typeof(SPDWorkflowReceiver).FullName);
            sb.AppendFormat("\t xmlns=\"http://schemas.microsoft.com/sharepoint/\">\n");
            sb.AppendFormat("\t\t <ElementManifests/>\n");
            sb.AppendFormat("</Feature>\n");

            if (!File.Exists(path) || overwrite)
            {
                File.WriteAllText(path, sb.ToString());
            }
        }

        /// <summary>
        /// Ensures that an directory exists
        /// </summary>
        private static void EnsurePathExists(string featurePath)
        {
            if (!Directory.Exists(featurePath))
            {
                Directory.CreateDirectory(featurePath);
            }
        }
    }
}